package com.cos.hospital.ui.login;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.cos.hospital.R;
import com.cos.hospital.dao.UCheckDB;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.retrofit.MyObserver;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.ui.main.MainActivity;
import com.jude.utils.JUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 启动页面
 */
public class LaunchActivity extends BaseActivity {
    public static final int SCHEDULE_CHANGE = 1500;
    private RxPermissions rxPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int layout() {
        return 0;
    }

    @Override
    protected void init() {
        //将window的背景图设为空 二维码
//        getWindow().setBackgroundDrawable(null);
//        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams
//            .MATCH_PARENT);
//        ImageView loadingImage = new ImageView(this);
//        loadingImage.setBackgroundResource(R.mipmap.bg_qrcode);
//        addContentView(loadingImage, params);

        rxPermissions = new RxPermissions(this);
        boolean yby = SPUtil.isNewestVersion();
        if (!yby) {//每次更新版本，让用户重新登录
            removeAuthor();
            SPUtil.saveNewestVersion(true);
        }
    }

    @Override
    protected void logic() {
        if (!JUtils.isNetWorkAvilable()) {
            showNetWorkExceptionDialog();
            return;
        }
        if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            toNext();
        } else {
            showRequestPermissionDialog();
        }
    }

    private void showRequestPermissionDialog() {
        String s = getString(R.string.app_name) + "需要获取存储空间权限，以保证程序的正常运行。";
        SpannableStringBuilder builder = new SpannableStringBuilder(s);
        builder.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.green_bg)), 7, 11, Spannable
            .SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(new ForegroundColorSpan(Color.BLACK), 12, s.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        new AlertDialog.Builder(this, R.style.BDAlertDialog)
            .setCancelable(false)
            .setTitle("权限申请")
            .setMessage(builder)
            .setNegativeButton("取消", (dialogInterface, i) -> finish())
            .setPositiveButton("去授权", (dialogInterface, i) -> {
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {
                            toNext();
                        } else {
                            MyUtil.getInstance().toSetting(context, "需要获取存储空间权限，以保证程序的正常运行。", 10, true);
                        }
                    });
            })
            .show();
    }

    private void toNext() {
//        if (true) {
//            startActivity(new Intent(this, LaboratoryActivity.class));
//            return;
//        }
        if (SPUtil.isLogin()) {
            UCheckDB.check(this, getServes(), new UCheckDB.CheckListener() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    addEvent(disposable);
                }

                @Override
                public void onEnd() {
                    changeToMainActivity();
                }
            }).checkVersion("登录中...");
        } else {
            changeToMainActivity();
        }
    }

    private void changeToMainActivity() {
        Observable.timer(SCHEDULE_CHANGE, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new MyObserver<Long>() {
                @Override
                public void onSubscribe(Disposable d) {
                    super.onSubscribe(d);
                    addEvent(d);
                }

                @Override
                public void onNext(Long aLong) {
                    Intent intent = new Intent();
                    if (SPUtil.isLogin()) {
                        intent.setClass(LaunchActivity.this, MainActivity.class);
                    } else {
                        intent.setClass(LaunchActivity.this, LoginActivity.class);
                    }
                    startActivity(intent);
                    finish();
                }
            });
    }

    private void showNetWorkExceptionDialog() {
        Dialog mDialog = new Dialog(this, R.style.SakuraDialog);
        View view = View.inflate(this, R.layout.dialog_network, null);
        Button cancel = view.findViewById(R.id.networkCancel);
        Button sure = view.findViewById(R.id.networkSure);
        mDialog.setContentView(view);
        mDialog.show();
        mDialog.setCanceledOnTouchOutside(false);
        cancel.setOnClickListener(v -> {
            mDialog.dismiss();
            finish();
        });
        sure.setOnClickListener(v -> {
            mDialog.dismiss();
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            finish();
        });
    }

    public void removeAuthor() {
        SPUtil.clearUserInfo();
    }

}
